package org.ziky.common.framework.wicket.util;

import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.ziky.common.framework.wicket.behavior.FwAttributeModifier;
import org.ziky.common.util.string.StrUtil;

public class AttributeUtil {
    public static void setAttribute(Component component, String attribute, String value) {
        component.add(FwAttributeModifier.replace(attribute, value));
    }

    public static String getAttribute(Component component, String attribute) {
        String attrValue = null;
        List<? extends Behavior> lstBehaviors = component.getBehaviors();
        for (Behavior behavior : lstBehaviors) {
            if (behavior instanceof AttributeModifier
                    && attribute.equals(((FwAttributeModifier) behavior).getAttribute())) {
                attrValue = ((FwAttributeModifier) behavior).getValue();
                break;
            }
        }
        return attrValue != null ? attrValue : StrUtil.trimToEmpty(component.getMarkupAttributes().getString(attribute));
    }

    public static void appendAttribute(Component component, String attribute, String value) {
        component.add(FwAttributeModifier.append(attribute, value));
    }

    public static void prependAttribute(Component component, String attribute, String value) {
        component.add(FwAttributeModifier.prepend(attribute, value));
    }

    public static void replaceAttribute(Component component, String attribute, String value) {
        component.add(FwAttributeModifier.replace(attribute, value));
    }

    public static void removeAttribute(Component component, String attribute) {
        component.add(FwAttributeModifier.remove(attribute));
    }
}
